package commands;

import info.lundin.math.Eval;
import info.lundin.math.cannotConvertException;

import java.util.Hashtable;

import bot.CommandBot;


public class Calc implements Command {
	private Hashtable<String, String> table;

	@Override
	public String getCommandName() {
		return "c";
	}

	public Calc() {
		table = new Hashtable<String, String>();
	}

	@Override
	public boolean execCommand(String channel, String sender, String login,
			String hostname, String message, CommandBot bot) {
		if (message.startsWith(" ")) {
			return eval(channel, message, bot);
		} else if (message.startsWith("set ")) {
			return setVariable(channel, message, bot);
		}
		return false;
	}

	@Override
	public boolean execCommand(String sender, String login, String hostname,
			String message, CommandBot bot) {
		if (message.startsWith(" ")) {
			return eval(sender, message, bot);
		} else if (message.startsWith("set ")) {
			return setVariable(sender, message, bot);
		}
		return false;
	}

	private boolean setVariable(String channel, String message, CommandBot bot) {
		String[] split = message.substring(4).split("=");
		if (split.length == 2) {
			table.put(split[0], split[1]);
			bot.sendMessage(channel, split[0]+" = "+split[1], true);
		} else {
			bot.sendMessage(channel, "---", true);
		}
		return true;
	}

	private boolean eval(String channel, String message, CommandBot bot) {
		Eval eval = new Eval();
		try {
			double out = eval.eval(message, table);
			bot.sendMessage(channel, "" + out, true);
		} catch (cannotConvertException e) {
			bot.sendMessage(channel, e.getMessage(), true);
		}
		return true;
	}

}
